package com.test.case5;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author:wyf
 * @Description:计数方式一  原子类，无锁实现，采用CAS算法，性能高于一般的有锁算法
 * @Date:Created in 11:10 2021/6/29
 * @Modified By:
 */
public class Counter1 {
    public static AtomicLong inc = new AtomicLong();

    public void increase(){
        inc.getAndIncrement();
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            inc.set(0);
            count();
        }
    }

    private static void count() throws InterruptedException {
        final Counter1 c1 = new Counter1();
        Thread th = null;
        Long t1 = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            th = new Thread(){
                @Override
                public void run() {
                    for (int j = 0; j < 10000; j++) {
                        c1.increase();
                    }
                }
            };
            th.start();
            th.join();
        }
        long t2 = System.currentTimeMillis();
        System.out.println("Counter1 , "+String.format("结果：%s,耗时(ms)：%s", c1.inc, (t2 - t1)));
    }
}
